/*
 * @Author: Guojian Wang 1085844536@qq.com
 * @Date: 2022-12-15 22:14:22
 * @LastEditTime: 2022-12-17 01:05:58
 * @LastEditors: Guojian Wang 1085844536@qq.com
 * @FilePath: \CloundMusic\pages\recommendSong\recommendSong.js
 * @Description:
 */
import request from '../../../utils/request';
import PubSub from 'pubsub-js';

Page({
    /**
     * 页面初始数据
     */
    data: {
        // 天
        day: '',
        // 月
        month: '',
        // 推荐列表数据
        recommendList: [],
        // 点击音乐的下标
        index: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     * @param {Object} options 参数
     */
    onLoad(options) {
        // 判断用户是否登录
        let userInfo = wx.getStorageSync('userInfo');
        if (!userInfo) {
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                success: () => {
                    // 跳转至登录界面
                    wx.reLaunch({
                        url: '/pages/login/login',
                    });
                },
            });
        }

        // 更新日期的状态数据
        this.setData({
            day: new Date().getDate(),
            month: new Date().getMonth() + 1,
        });

        // 获取每日推荐的数据
        this.getRecommendList();

        // 订阅来自 songDetail 页面发布的消息
        PubSub.subscribe('switchType', (msg, type) => {
            let { recommendList, index } = this.data;
            if (type === 'pre') {
                // 上一首
                index === 0 && (index = recommendList.length);
                index -= 1;
            } else {
                // 下一首
                index === recommendList.length - 1 && (index = -1);
                index += 1;
            }

            // 更新下标
            this.setData({
                index,
            });

            let musicId = recommendList[index].id;
            // 将 musicId 回传给 songDetail 页面
            PubSub.publish('musicId', musicId);
        });
    },

    /**
     * 获取用户每日推荐的数据
     */
    async getRecommendList() {
        let recommendListData = await request('/recommend/songs');
        this.setData({
            recommendList: recommendListData.data.dailySongs,
        });
    },

    /**
     * 跳转至 songDetail 页面
     */
    toSongDetail(event) {
        let { song, index } = event.currentTarget.dataset;

        this.setData({ index: index });

        // 路由跳转传参：query参数
        wx.navigateTo({
            // 不能直接将 song 对象作为参数传递，长度过长，会被自动截取掉
            // url: '/pages/songDetail/songDetail?song=' + JSON.stringify(song),
            url: '/songPackage/pages/songDetail/songDetail?musicId=' + song.id,
        });
    },

    onReady() {},

    onShow() {},

    onHide() {},

    onUnload() {},

    onShareAppMessage() {},
});
